package cn.hhchat.wp.entity;

import cn.hhchat.wp.dto.form.RegisterForm;
import cn.hhchat.wp.dto.form.UserInfoEditForm;
import cn.hhchat.wp.dto.user.SimpleUser;
import cn.hhchat.wp.enums.GradeEnum;
import cn.hhchat.wp.enums.SexEnum;
import org.hibernate.annotations.*;
import org.hibernate.annotations.CascadeType;
import javax.persistence.*;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

/**
 * Created this one by HMH on 2017/10/22.
 */
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "user_entity")
public class UserEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String name;

    @Column(nullable = false)
    @Enumerated(EnumType.STRING)
    private SexEnum sex;

    @Column(nullable = false)
    @Enumerated(EnumType.STRING)
    private GradeEnum grade;

    @Column(unique = true, nullable = false)
    private String email;

    @Column(unique = true, nullable = false)
    private String username;

    @Column(nullable = false)
    private String password;

    private Date lastPwdChangeDate;

    @ManyToMany
    @Cascade(CascadeType.SAVE_UPDATE)
    private List<RoleEntity> roles;

    public SimpleUser toSimpleUser() {
        SimpleUser simpleUser = new SimpleUser();
        simpleUser.setId(this.id);
        simpleUser.setName(this.name);
        simpleUser.setUsername(this.username);
        simpleUser.setEmail(this.email);
        simpleUser.setGrade(this.grade.name());
        simpleUser.setSex(this.sex.name());
        simpleUser.setPrivileges(this.roles.stream().map(RoleEntity::getName).distinct().collect(Collectors.toList()));
        return simpleUser;
    }

    public UserEntity(RegisterForm form) {
        this.name = form.getName();
        this.username = form.getUsername();
        this.sex = SexEnum.fromString(form.getSex(),"性别");
        this.grade = GradeEnum.fromString(form.getGrade(), "年级");
        this.password = form.getPwd();
        this.roles = new ArrayList<>();
        this.email = form.getEmail();
        this.lastPwdChangeDate = new Date();
    }

    public UserEntity edit(UserInfoEditForm form) {
        this.sex = SexEnum.fromString(form.getSex(),"性别");
        this.grade = GradeEnum.fromString(form.getGrade(), "年级");
        this.password = form.getPwd();
        this.email = form.getEmail();
        this.lastPwdChangeDate = new Date();
        return this;
    }

    @Override
    public boolean equals(Object obj) {
        return obj instanceof UserEntity && (this.id.equals(((UserEntity) obj).id) || this.email.equals(((UserEntity) obj).email)||this.username.equals(((UserEntity) obj).username));
    }
}
